package com.example.dingtalk.controller;


import com.aliyun.dingtalkworkflow_1_0.models.*;
import com.example.dingtalk.service.impl.OaServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Description :
 * @Author : Bruce Lee
 * @CreateTime : 2024/5/22
 */

@RestController
@Slf4j
@RequestMapping("oa")
public class OaController {

    @Resource
    private OaServiceImpl oaService;

    /**
     * 根据实例id获取审批实例详情
     *
     * @param processInstanceId
     * @throws Exception
     */
    @GetMapping("getProcessInstance")
    public void getProcessInstance(String processInstanceId) throws Exception {
        GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult processInstance = oaService.getProcessInstance(processInstanceId);
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(processInstance);
        System.out.println(s);
    }

    @GetMapping("ids")
    public void getProcessIds() throws ApiException {
        List<String> approvalIds = oaService.getApprovalIds();
        for (String approvalId : approvalIds) {
            System.out.println(approvalId);
        }
    }


    /**
     * 根据实例id获取审批实例详情
     *
     * @param
     * @throws Exception
     */
    @GetMapping("detail")
    public void getProcessDetail(@RequestBody List<String> ids) throws Exception {
        for (String id : ids) {
            GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult instance = oaService.getProcessInstance(id);
            ObjectMapper mapper = new ObjectMapper();
            String s = mapper.writeValueAsString(instance);
            System.out.println(s);
        }

    }

    /**
     * 存储代审批数据
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/process")
    public ResponseEntity<String> processApprovalIds() throws Exception {
        oaService.processApprovalIds();
        return ResponseEntity.ok("Processing completed.");
    }

    /**
     * 存储审批完成的审批单
     * @throws Exception
     */
    @GetMapping("processAll")
    public void processAllComplete() throws Exception {
        oaService.loopProcessingApproval();
        System.out.println("存储完成");
    }

    /**
     * 导出钉钉数据
     *
     * @param response
     * @param flag
     */
    @GetMapping("/export-dingData")
    public void exportDingData(HttpServletResponse response,
                               @RequestParam("start") String start,
                               @RequestParam("end") String end,
                               @RequestParam(value = "flag", defaultValue = "false") boolean flag,
                               @RequestParam("status") String status) throws Exception {


        log.info("用户执行导出,状态:{},时间范围:{}-{},导出范围:{}", status, start, end, flag);
        oaService.refreshStatus();
        byte[] bytes = new byte[0];
        if ("待审批".equals(status)) {
            bytes = oaService.exportExpensesToExcel(start, end, flag);
        }

        if ("已完成".equals(status)) {
            bytes = oaService.exportExcelIsComplete(start, end, flag);
        }
        // 设置文件名为 "expenses_yyyyMMdd.xlsx"
        extracted(response, bytes);

    }
    /**
     * 根据时间范围是否导出过导出待审批数据
     * @param response
     * @param start
     * @param end
     * @param flag  true 全量导出（未审批）  false 导出增量（未审批的）
     * @throws IOException
     */
    @GetMapping("/excel/exporter")
    public void exportAllExpensesByDay(HttpServletResponse response,
                                       @RequestParam("start") String start,
                                       @RequestParam("end") String end,
                                       @RequestParam(value = "flag", defaultValue = "false") boolean flag,
                                       @RequestParam("status") String status) throws IOException {

        log.info("用户执行导出,状态:{},时间范围:{}-{},导出范围:{}", status, start, end, flag);
        oaService.refreshStatus();

        byte[] bytes = oaService.exportExpensesToExcel(start, end,flag);
        // 设置文件名为 "expenses_yyyyMMdd.xlsx"
        extracted(response, bytes);
    }

    private static void extracted(HttpServletResponse response, byte[] bytes) throws IOException {
        String fileName="expenses_data.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.getOutputStream().write(bytes);
        response.getOutputStream().flush();
    }
    /**
     * 根据时间范围导出数据已审批数据
     * @param response
     * @param startDate
     * @param endDate
     * @param flag true 全量导出（已审批+待审批）  false 导（已审批的）
     * @throws IOException
     */
    @GetMapping("/excel/complete")
    public void exportAccountsPayable(HttpServletResponse response,
                                      @RequestParam("startDate") String startDate,
                                      @RequestParam("endDate") String endDate,
                                      @RequestParam(value = "flag", defaultValue = "false") boolean flag) throws IOException {

        byte[] bytes = oaService.exportExcelIsComplete(startDate, endDate,flag);
        // 设置文件名为 "expenses_yyyyMMdd.xlsx"
        extracted(response, bytes);
    }





    /**
     * 根据审批人查询待办审批流
     * @throws Exception
     */
    /*@GetMapping("getProcessListByApprover")
    public void getProcessListByPage() throws Exception {

        // 获取所有审批实例ID列表
        ArrayList<String> processInstanceIdList = new ArrayList<>();
        // 每页大小
        Long pageSize = 20L;
        // 待办审批流状态: RUNNING、TERMINATED、COMPLETED
//        String statuses = "RUNNING";
        String statuses = "COMPLETED";


        // 获取查询的起始时间，默认结束时间是函数调用时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        // 往前推3个月
        c.add(Calendar.MONTH, -3);
        Date time = c.getTime();

        // 获取审批模板code
        String processCode = "PROC-3915C166-DD31-422F-935D-58C1ACC14F7F";
        ListProcessInstanceIdsResponseBody.ListProcessInstanceIdsResponseBodyResult result = oaService.getProcessListByPage(time.getTime(), processCode, 1L, pageSize, statuses);

        if (result != null) {
            result.getList().forEach(processInstanceId -> {
                try {
                    GetProcessInstanceResponse processInstance = oaService.getProcessInstance(processInstanceId);
                    if (processInstance.getBody().getResult().getApproverUserIds() != null && processInstance.getBody().getResult().getApproverUserIds().contains(user.getUserId())) {
                        List<GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResultTasks> tasks = processInstance.getBody().getResult().getTasks();
                        processInstanceIdList.add(processInstanceId);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (result.getNextToken() != null) {
                result = oaService.getProcessListByPage(time.getTime(), processCode, Long.valueOf(result.getNextToken()), pageSize, statuses);
                result.getList().forEach(processInstanceId -> {
                    try {
                        GetProcessInstanceResponse processInstance = oaService.getProcessInstance(processInstanceId);
                        if (processInstance.getBody().getResult().getApproverUserIds() != null && processInstance.getBody().getResult().getApproverUserIds().contains(user.getUserId())) {
                            processInstanceIdList.add(processInstanceId);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        }

        processInstanceIdList.forEach(processInstanceId -> {
                    log.info("审批流列表：" + processInstanceId);
                }
        );
        log.info("审批流列表数量：" + processInstanceIdList.size());
    }*/

    //获取审批组件processCode
    /*public static void main(String[] args) throws Exception {
        com.aliyun.dingtalkworkflow_1_0.Client client = OaServiceImpl.createClient();
        com.aliyun.dingtalkworkflow_1_0.models.ListUserVisibleBpmsProcessesHeaders listUserVisibleBpmsProcessesHeaders = new com.aliyun.dingtalkworkflow_1_0.models.ListUserVisibleBpmsProcessesHeaders();
        listUserVisibleBpmsProcessesHeaders.xAcsDingtalkAccessToken = "bdc6fd6c93753309b6d99f40200b4791";
        com.aliyun.dingtalkworkflow_1_0.models.ListUserVisibleBpmsProcessesRequest listUserVisibleBpmsProcessesRequest = new com.aliyun.dingtalkworkflow_1_0.models.ListUserVisibleBpmsProcessesRequest()
//                .setUserId("13335729131062710")
                .setMaxResults(100L)
                .setNextToken(100L);
        try {
            ListUserVisibleBpmsProcessesResponse listUserVisibleBpmsProcessesResponse = client.listUserVisibleBpmsProcessesWithOptions(listUserVisibleBpmsProcessesRequest, listUserVisibleBpmsProcessesHeaders, new RuntimeOptions());
            ListUserVisibleBpmsProcessesResponseBody.ListUserVisibleBpmsProcessesResponseBodyResult result = listUserVisibleBpmsProcessesResponse.getBody().getResult();
            List<ListUserVisibleBpmsProcessesResponseBody.ListUserVisibleBpmsProcessesResponseBodyResultProcessList> processList = result.getProcessList();
            for (ListUserVisibleBpmsProcessesResponseBody.ListUserVisibleBpmsProcessesResponseBodyResultProcessList list : processList) {
                System.out.println(list.getProcessCode()+list.getName());
            }
            System.out.println(result.getNextToken());
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        }
    }*/
}
